<?php
/**
 * 工具函数类
 */
class Tools
{

    /**
     * 生成盐字符串
     * @param int 盐长度，默认为10
     * @return string 盐字符串
     */
    public static function getSalt($length = 10, $onlyNumber = false)
    { 
        $characters = $onlyNumber ? '0123456789' : '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $startIndex = 0;
            if($onlyNumber && $i === 0) $startIndex = 1;
            $randomString .= $characters[rand($startIndex, $charactersLength - 1)];
        }
        return $randomString;
    }

    /**
     * 生成密码
     * @param string $password 明文密码
     * @param string $salt 盐
     * @return string 加密后的密码
     */
    public static function getPassword($password, $salt){
      return sha1($password.$salt);
    }

    /**
     * 将列表中的keyField复制到key字段中，供React前端遍历使用
     */
    public static function setListKey(& $list, $keyField)
    {
        foreach ($list as $key => $value) {
            $list[$key]['key'] = $value[$keyField];
        }
    }

    /**
     * 设置文件下载的文件头
     * @param [type] $filename
     * @return void
     */
    public static function setDownloadHeader($filename, $contentType = false) {
      $encoded_filename = urlencode($filename);
      $encoded_filename = str_replace("+", "%20", $encoded_filename);

      //设置文件头
      $ua = $_SERVER["HTTP_USER_AGENT"];
      header("Content-Type: application/octet-stream");
      if (preg_match("/MSIE/", $ua) || preg_match("/Trident/", $ua)) {
          header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
      } elseif (preg_match("/Firefox/", $ua)) {
          header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
      } else {
          header('Content-Disposition: attachment; filename="' . $filename . '"');
      }
      header("Content-Transfer-Encoding: binary");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Pragma: public");
      if($contentType){
        header("Content-Type: $contentType");
      }
    }

    /**
     * 获取Limit字串
     * @return string limit
     */
    public static function getPageLimit($page = 1, $limit = 10)
    {
        $offset = ($page - 1) * $limit;
        return $offset.','.$limit;
    }

    /**
     * 获取百分制的比例
     * @param int $num 除数
     * @param int $total 被除数
     * @return void
     */
    public static function getProgressPercent($num, $total){
      if($total > 0) {
        $percent = ($num / $total) * 100.0;
        if($percent > 1) {
          // 大于1%的，下取整
          $percent = floor($percent);
        }else if($percent > 0) {
          // 大于0小于1%的，设置为1%
          $percent = 1;
        }
        return $percent;
      }else {
        return 0;
      }
    }
}
